package org.common.controller;

import org.common.entity.UserEntity;
import org.common.service.mongo.UserService;
import org.common.utils.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang3.RandomStringUtils;
import org.common.service.cache.RedisCache;
import org.common.config.NacosConfig;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/system")
public class SystemController {

    @Resource
    UserService userService;


    @Resource
    RedisCache redisCache;

    @Resource
    NacosConfig nacosConfig;


    @Autowired
    private static final Logger logger = LoggerFactory.getLogger(System.class);


    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public ApiResponse GetTest() {
        System.out.println(String.format("............%s.........", nacosConfig.getName()));
        return ApiResponse.success("user not found");
    }

    /**
     * @return token String
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)

    public ApiResponse Login(@RequestBody UserEntity user) {

        List<UserEntity> users = userService.findByUsernameAndPassword(user.getUsername(), user.getPassword());
        if (users.size() == 1) {
            String token = RandomStringUtils.randomAlphanumeric(24).toLowerCase();
            redisCache.setCacheObject(token, user.getId());
            return ApiResponse.success(token);
        } else
            return ApiResponse.fail("user not found");
    }

    /**
     * @param user 创建用户， 旨在与使用各种组件与业务无关
     * @return
     */
    @RequestMapping(value = "/user/create", method = RequestMethod.POST)

    public ApiResponse UserCreate(@RequestBody UserEntity user) {

        String userName = user.getUsername();

        List<UserEntity> users = userService.getUserByUsername(userName);

        if (users.size() == 0) {
            logger.info("User created");
            UserEntity userI = userService.saveUser(user);
            return ApiResponse.success(userI);
        }

        logger.info("User existed");
        return ApiResponse.success(users.stream().findFirst());
    }

}
